package com.ausoo.rss.service;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ausoo.rss.model.RssEntry;
import com.sun.syndication.fetcher.FetcherException;
import com.sun.syndication.io.FeedException;

public class FreshLinkServiceImpl implements IFreshLinkService {
	private static final Log log = LogFactory
			.getLog(FreshLinkServiceImpl.class);

	private String linksFilePath;
	private IRssService rssService;

	public void setRssService(IRssService rssService) {
		this.rssService = rssService;
	}

	public void setLinksFilePath(String linksFilePath) {
		this.linksFilePath = linksFilePath;
	}

	public List getFreshLinks() {
		List lines = null;
		try {
			lines = FileUtils.readLines(getLinksFile(), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lines;
	}

	public void writeFreshLinks(List<String> links) {
		try {
			FileUtils.writeLines(getLinksFile(), "UTF-8", links);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private File getLinksFile() {
		File file = new File(linksFilePath);

		return file;
	}

	public long lastModified() {
		return this.getLinksFile().lastModified();
	}

	public void collectLinks() {
		List<RssEntry> entries;
		List<String> freshLinks = new ArrayList<String>();
		log.debug(new Date() + "");

		try {
			entries = rssService.fetchRss();
			for (RssEntry entry : entries) {
				if (entry.getPublishDate().getTime() > lastModified()) {
					freshLinks.add(entry.getUrlForIndex());
				}
			}

			if (freshLinks.size() > 0) {
				writeFreshLinks(freshLinks);
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FeedException e) {
			e.printStackTrace();
		} catch (FetcherException e) {
			e.printStackTrace();
		}

	}
}
